package etnorservice.etnor_service.controller;

import etnorservice.etnor_service.service.AccessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class AccessController {

    @Autowired
    private AccessService accessService;

    @GetMapping("/access/{directoryPath}")
    public ResponseEntity<String> accessDirectory(@PathVariable String directoryPath, HttpServletRequest request) {
        String ipAddress = request.getRemoteAddr();

        if (accessService.isRestrictedDirectory(directoryPath)) {
            accessService.logAccess(ipAddress, directoryPath);

            if (accessService.isIpBlocked(ipAddress)) {
                return new ResponseEntity<>("Your IP address has been blocked due to multiple unauthorized access attempts.", HttpStatus.FORBIDDEN);
            }

            long accessCount = accessService.countAccessLogsForIp(ipAddress);
            if (accessCount > 1) {
                accessService.blockIp(ipAddress);
                return new ResponseEntity<>("Your IP address has been blocked due to multiple unauthorized access attempts.", HttpStatus.FORBIDDEN);
            }

            return new ResponseEntity<>("Warning: You are attempting to access a restricted directory. Please do not attempt any illegal activities.", HttpStatus.FORBIDDEN);
        }

        return new ResponseEntity<>("Directory not found.", HttpStatus.NOT_FOUND);
    }
}